﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using System.Text.RegularExpressions;

namespace AsscerMVCN2512.Controllers
{
    public class EmpolyController : Controller
    {
        private readonly AssetDBEntities1 db = new AssetDBEntities1();

        // 员工列表页面
        public ActionResult Index()
        {
            return View();
        }

        // 获取员工列表数据 
        [HttpPost]
        public ActionResult GetEmployeeList(int page = 1, int limit = 10, string EmpolyName = "",
                                          int? DeptID = null, int? RoleID = null, string EmpolySex = "")
        {
            try
            {
                var query = from e in db.EmpolyInfo
                            join d in db.DeptInfo on e.DeptID equals d.DeptID into dept
                            from d in dept.DefaultIfEmpty()
                            join r in db.RoleInfo on e.RoleID equals r.RoleID into role
                            from r in role.DefaultIfEmpty()
                            select new
                            {
                                e.EmpolyID,
                                e.EmpolyNum,
                                e.EmpolyName,
                                e.EmpolySex,
                                e.EmpolyIdCard,
                                DeptName = d != null ? d.DeptName : "",
                                e.EmpolyLevel,
                                RoleName = r != null ? r.RoleName : "",
                                e.InductionDate,
                                e.DepartureDate,
                                e.EmpolyReMark,
                                e.RoleID,
                                e.DeptID
                            };

                // 查询条件
                if (!string.IsNullOrEmpty(EmpolyName))
                    query = query.Where(e => e.EmpolyName.Contains(EmpolyName));

                if (DeptID.HasValue && DeptID > 0)
                    query = query.Where(e => e.DeptID == DeptID);

                if (RoleID.HasValue && RoleID > 0)
                    query = query.Where(e => e.RoleID == RoleID);

                if (!string.IsNullOrEmpty(EmpolySex))
                    query = query.Where(e => e.EmpolySex == EmpolySex);

                var total = query.Count();
                var data = query.OrderByDescending(e => e.EmpolyID) // 按ID倒序，新数据在前
                              .Skip((page - 1) * limit)
                              .Take(limit)
                              .ToList();

                return Json(new { code = 0, msg = "成功", count = total, data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        // 获取部门列表
        [HttpPost]
        public ActionResult GetDeptList()
        {
            try
            {
                var data = db.DeptInfo.Select(d => new { d.DeptID, d.DeptName }).ToList();
                return Json(new { code = 0, msg = "成功", data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取部门列表失败：" + ex.Message });
            }
        }

        // 获取角色列表
        [HttpPost]
        public ActionResult GetRoleList()
        {
            try
            {
                var data = db.RoleInfo.Select(r => new { r.RoleID, r.RoleName }).ToList();
                return Json(new { code = 0, msg = "成功", data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取角色列表失败：" + ex.Message });
            }
        }

        // 添加员工（表单提交）
        [HttpPost]
        public ActionResult AddEmployee(EmpolyInfo employee)
        {
            try
            {
                // 验证员工编号唯一性
                var existingEmployee = db.EmpolyInfo.FirstOrDefault(e => e.EmpolyNum == employee.EmpolyNum);
                if (existingEmployee != null)
                {
                    return Json(new { code = 1, msg = "员工编号已存在，请使用其他编号" });
                }

                // 设置默认密码和头像
                employee.EmpolyPwd = "123456"; // 默认密码

                // 如果前端没有传递入职日期，使用当前日期
                if (employee.InductionDate == null || employee.InductionDate == DateTime.MinValue)
                {
                    employee.InductionDate = DateTime.Now;
                }

                db.EmpolyInfo.Add(employee);
                db.SaveChanges();

                return Json(new { code = 0, msg = "添加员工成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加员工失败：" + ex.Message });
            }
        }

        // 获取单个员工信息（用于编辑页面数据绑定）
        [HttpGet]
        public ActionResult GetEmployeeById(int id)
        {
            try
            {
                var employee = db.EmpolyInfo.Find(id);
                if (employee == null)
                {
                    return Json(new { code = 1, msg = "员工不存在" }, JsonRequestBehavior.AllowGet);
                }

                // 返回JSON格式数据
                return Json(new
                {
                    code = 0,
                    data = new
                    {
                        EmpolyID = employee.EmpolyID,
                        EmpolyNum = employee.EmpolyNum,
                        EmpolyName = employee.EmpolyName,
                        EmpolySex = employee.EmpolySex,
                        EmpolyIdCard = employee.EmpolyIdCard,
                        DeptID = employee.DeptID,
                        EmpolyLevel = employee.EmpolyLevel,
                        RoleID = employee.RoleID,
                        InductionDate = employee.InductionDate?.ToString("yyyy-MM-dd"),
                        DepartureDate = employee.DepartureDate?.ToString("yyyy-MM-dd"),
                        EmpolyReMark = employee.EmpolyReMark
                    }
                }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取员工信息失败：" + ex.Message }, JsonRequestBehavior.AllowGet);
            }
        }

        // 修改员工
        [HttpPost]
        public ActionResult UpdateEmployee(EmpolyInfo employee)
        {
            try
            {
                var existingEmployee = db.EmpolyInfo.Find(employee.EmpolyID);
                if (existingEmployee == null)
                {
                    return Json(new { code = 1, msg = "员工不存在" });
                }

                // 验证员工编号唯一性（排除当前员工）
                var existingWithSameNum = db.EmpolyInfo.FirstOrDefault(e => e.EmpolyNum == employee.EmpolyNum && e.EmpolyID != employee.EmpolyID);
                if (existingWithSameNum != null)
                {
                    return Json(new { code = 1, msg = "员工编号已存在，请使用其他编号" });
                }

                // 更新字段
                existingEmployee.EmpolyNum = employee.EmpolyNum;
                existingEmployee.EmpolyName = employee.EmpolyName;
                existingEmployee.EmpolySex = employee.EmpolySex;
                existingEmployee.EmpolyIdCard = employee.EmpolyIdCard;
                existingEmployee.DeptID = employee.DeptID;
                existingEmployee.EmpolyLevel = employee.EmpolyLevel;
                existingEmployee.RoleID = employee.RoleID;
                existingEmployee.InductionDate = employee.InductionDate;
                existingEmployee.DepartureDate = employee.DepartureDate;
                existingEmployee.EmpolyReMark = employee.EmpolyReMark;

                db.Entry(existingEmployee).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { code = 0, msg = "修改员工成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改员工失败：" + ex.Message });
            }
        }

        // 删除员工
        [HttpPost]
        public ActionResult DeleteEmployee(int id)
        {
            try
            {
                var employee = db.EmpolyInfo.Find(id);
                if (employee == null)
                {
                    return Json(new { code = 1, msg = "员工不存在" });
                }

                db.EmpolyInfo.Remove(employee);
                db.SaveChanges();
                return Json(new { code = 0, msg = "删除员工成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除员工失败：" + ex.Message });
            }
        }

        // 检查员工编号是否唯一
        [HttpPost]
        public ActionResult CheckEmpolyNum(string empolyNum, int? empolyId = null)
        {
            try
            {
                var existing = db.EmpolyInfo.FirstOrDefault(e => e.EmpolyNum == empolyNum);
                if (existing != null && (empolyId == null || existing.EmpolyID != empolyId))
                {
                    return Json(new { code = 1, msg = "员工编号已存在" });
                }
                return Json(new { code = 0 });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查失败：" + ex.Message });
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}